package com.shigen.demo.atguigu;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者消费者传统模式
 *
 * @author shigenfu
 * @date 2022/5/22 9:25 下午
 */

class Sharedata {

  private int number = 0;
  private Lock lock = new ReentrantLock();
  private Condition condition = lock.newCondition();

  public void increment() {
    lock.lock();
    try {
      // 1.判断
      while (number != 0) {
        // 等待，不生产
        condition.await();
      }
      // 2.干活儿
      number++;
      System.out.println(Thread.currentThread().getName() + " 生产 " + number);
      // 3.唤醒
      condition.signal();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public void decrement() {
    lock.lock();
    try {
      // 1.判断
      while (number == 0) {
        // 等待，不生产
        condition.await();
      }
      // 2.干活儿
      number--;
      System.out.println(Thread.currentThread().getName() + " 消费 " + number);
      // 3.唤醒
      condition.signal();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }
}


public class ProdConsumerTraditionDemo {

  public static void main(String[] args) {
    Sharedata sharedata = new Sharedata();
    for (int i = 0; i < 5; i++) {
      new Thread(() -> {
        sharedata.increment();
      }, String.valueOf(i)).start();
    }

    for (int i = 0; i < 5; i++) {
      new Thread(() -> {
        sharedata.decrement();
      }, String.valueOf(i)).start();
    }


  }

}
